﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Net.Security;
using System.Net.Cache;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;

namespace Common
{
    public abstract class HttpUtils
    {
        #region 静态公共函数

        #region 验证是否存在

        public static bool IsExist(string targetURL, Hashtable param, string meghod, Encoding encoding, Func<string, bool> callBack, Func<Exception, bool> exceptionHandle)
        {
            return IsExist(targetURL, string.Empty, new CookieContainer(), param, meghod, encoding, 120, true, callBack, exceptionHandle);
        }

        public static bool IsExist(string targetURL, string refererUrl, CookieContainer cc, Hashtable param, string meghod, Encoding encoding, int timeOut, bool keepAlive
            , Func<string, bool> callBack
            , Func<Exception, bool> exceptionHandle)
        {
            HttpWebResponse response = null;
            Stream responseStream = null;
            string str4;
            try
            {
                string s = "";
                foreach (DictionaryEntry entry in param)
                {
                    string str2 = entry.Key.ToString();
                    try
                    {
                        int indexof = GetIndexOfByRegex(str2);
                        if (str2.IndexOf(":replaceflag:") > 0)
                        {
                            str2 = str2.Substring(0, str2.IndexOf(":replaceflag:"));
                        }
                        else if (indexof > -1)
                        {
                            str2 = str2.Substring(0, indexof);
                        }
                        string str5 = s;
                        s = str5 + str2 + "=" + entry.Value.ToString() + "&";
                        continue;
                    }
                    catch
                    {
                        continue;
                    }
                }
                if (s.Length > 0)
                {
                    s = s.Substring(0, s.Length - 1);
                }
                byte[] bytes = encoding.GetBytes(s);
                if (targetURL.StartsWith("https", StringComparison.CurrentCultureIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(HttpUtils.CheckValidationResult);
                }
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
                if (WebRequest.GetSystemWebProxy() != null)
                {
                    request.Proxy = WebRequest.GetSystemWebProxy();
                }
                HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                request.CachePolicy = policy;
                request.Timeout = timeOut * 1000;
                request.KeepAlive = keepAlive;
                request.Method = meghod.ToUpper();
                //request.AllowAutoRedirect = false;
                bool flag = false;
                if (request.Method.ToUpper() == "POST")
                {
                    flag = true;
                }
                if (flag)
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = bytes.Length;
                }
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)";
                request.Referer = refererUrl;
                request.CookieContainer = cc;
                if (flag)
                {
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                response = (HttpWebResponse)request.GetResponse();
                response.Cookies = cc.GetCookies(request.RequestUri);
                responseStream = response.GetResponseStream();
                str4 = new StreamReader(responseStream, encoding).ReadToEnd();

                return callBack(str4);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(targetURL + "\r\n" + refererUrl + "\r\n" + cc.Count.ToString() + "\r\n" + meghod + "\r\n" + encoding.EncodingName + "\r\n" + exception.ToString());
                str4 = null;
                return exceptionHandle(exception);
            }
            finally
            {
                try
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                    if (responseStream != null)
                    {
                        responseStream.Close();
                    }
                    //GC.Collect();
                }
                catch
                {
                }
            }
        }

        #endregion

        #region 调用Http
        public static string PostAndGetHTML(string targetURL, Hashtable param, string meghod, Encoding encoding, Action<Exception> exceptionHandle)
        {
            return PostAndGetHTML(targetURL, string.Empty, new CookieContainer(), param, meghod, encoding, 120, true, exceptionHandle);
        }

        public static string PostAndGetHTML(string targetURL, string refererUrl, CookieContainer cc, Hashtable param, string meghod, Encoding encoding, int timeOut, bool keepAlive
    , Action<Exception> exceptionHandle)
        {
            HttpWebResponse response = null;
            Stream responseStream = null;
            string str4;
            try
            {
                string s = "";
                foreach (DictionaryEntry entry in param)
                {
                    string str2 = entry.Key.ToString();
                    try
                    {
                        int indexof = GetIndexOfByRegex(str2);
                        if (str2.IndexOf(":replaceflag:") > 0)
                        {
                            str2 = str2.Substring(0, str2.IndexOf(":replaceflag:"));
                        }
                        else if (indexof > -1)
                        {
                            str2 = str2.Substring(0, indexof);
                        }
                        string str5 = s;
                        s = str5 + str2 + "=" + entry.Value.ToString() + "&";
                        continue;
                    }
                    catch
                    {
                        continue;
                    }
                }
                if (s.Length > 0)
                {
                    s = s.Substring(0, s.Length - 1);
                }
                byte[] bytes = encoding.GetBytes(s);
                if (targetURL.StartsWith("https", StringComparison.CurrentCultureIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(HttpUtils.CheckValidationResult);
                }
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
                if (WebRequest.GetSystemWebProxy() != null)
                {
                    request.Proxy = WebRequest.GetSystemWebProxy();
                }
                HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                request.CachePolicy = policy;
                request.Timeout = timeOut * 1000;
                request.KeepAlive = keepAlive;
                request.Method = meghod.ToUpper();
                //request.AllowAutoRedirect = false;
                bool flag = false;
                if (request.Method.ToUpper() == "POST")
                {
                    flag = true;
                }
                if (flag)
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = bytes.Length;
                }
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)";
                request.Referer = refererUrl;
                request.CookieContainer = cc;
                if (flag)
                {
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                response = (HttpWebResponse)request.GetResponse();
                response.Cookies = cc.GetCookies(request.RequestUri);
                responseStream = response.GetResponseStream();
                str4 = new StreamReader(responseStream, encoding).ReadToEnd();
            }
            catch (Exception exception)
            {
                exceptionHandle(exception);
                Debug.WriteLine(targetURL + "\r\n" + refererUrl + "\r\n" + cc.Count.ToString() + "\r\n" + meghod + "\r\n" + encoding.EncodingName + "\r\n" + exception.ToString());
                str4 = null;
            }
            finally
            {
                try
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                    if (responseStream != null)
                    {
                        responseStream.Close();
                    }
                }
                catch
                {
                }
            }
            return str4;
        }

        #endregion

        #endregion

        #region 获取位数
        private static int GetIndexOfByRegex(string Source)
        {
            string input = Source;
            try
            {
                string regex = ":replaceflag[0-9]{0,4}:";
                Regex regex2 = new Regex(regex, RegexOptions.IgnoreCase);
                Match match = regex2.Match(Source);
                if (match.Success)
                {
                    return Source.IndexOf(match.Value);
                }
            }
            catch (Exception exception)
            {
                string msg = "" + exception.Message + exception.StackTrace;
                Console.WriteLine(msg);
            }
            return -1;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        #endregion
    }
}
